﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;


using System.Threading.Tasks;

using VideoClubGorbea.Model;
using VideoClubGorbea.ServicesClient;
using VideoClubGorbea.Common.Interfaces;
using VideoClubGorbea.ServicesClient.Interfaces;


namespace VideoClubGorbea.Web.Controllers
{
    public class HomeController : AsyncController
    {
        public IMovieServicesProxy Factory { get; set; }

        public HomeController(IMovieServicesProxy factory)
        {
            this.Factory = factory;
        }

        public ActionResult Index(int? page)
        {
            var latestMovieTask = Factory.GetLatestMoviesAsync(page);
            latestMovieTask.Start();
            ViewBag.Message = "¡Bienvenido a la mayor tienda online de contenidos digitales!.";
            latestMovieTask.Result.ToList().ForEach(x =>
            {
                var y = x.Posters.ToList();
                x.Posters.Clear();
                Image poster = y.FirstOrDefault(m => { return (m.Url.Contains("thumb")); });
                x.Posters.Add(poster ?? y.First());
            });
            return Request.IsAjaxRequest() ?
        (ActionResult)PartialView("Index_partial", latestMovieTask.Result) :
        (ActionResult)View(latestMovieTask.Result);

        }

        public ActionResult About()
        {
            ViewBag.Message = "Your quintessential app description page.";
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get), HandleError]
        public void SearchMoviesAsync(string term)
        {
            AsyncManager.OutstandingOperations.Increment();
            var searchMovieTask = Factory.SearchMoviesAsync(term);
            searchMovieTask.ContinueWith((x) =>
            {
                AsyncManager.Parameters["movies"] = searchMovieTask.Result;
                AsyncManager.OutstandingOperations.Decrement();
            });
            searchMovieTask.Start();
        }

        public ActionResult SearchMoviesCompleted(IEnumerable<Movie> movies)
        {
            var moviDTOs = movies.Select(x => new { label = x.Title, MovieID = x.Id }).ToList();
            return Json(moviDTOs, JsonRequestBehavior.AllowGet);
        }



        public ActionResult Contact()
        {
            ViewBag.Message = "Your quintessential contact page.";

            return View();
        }
    }

}
